package com.bidv.wcm;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.tagext.TryCatchFinally;

import com.bidv.BO.PaginationBO;
import com.bidv.util.Constant;
import com.bidv.util.DateUtil;
import com.bidv.util.Pagination;
import com.bidv.util.StringUtil;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;
import com.ibm.workplace.wcm.api.Content;
import com.ibm.workplace.wcm.api.DocumentId;
import com.ibm.workplace.wcm.api.DocumentIdIterator;
import com.ibm.workplace.wcm.api.DocumentLibrary;
import com.ibm.workplace.wcm.api.DocumentTypes;
import com.ibm.workplace.wcm.api.ImageComponent;
import com.ibm.workplace.wcm.api.LibraryImageComponent;
import com.ibm.workplace.wcm.api.TextComponent;
import com.ibm.workplace.wcm.api.WCM_API;
import com.ibm.workplace.wcm.api.Workspace;

@WebServlet("/News")
public class News extends HttpServlet {

	private static final String BANNER_SPDV = "banner_spdv";
	private static final String BANNER_TINCNTT = "banner_tincntt";
	private static final String BANNER_TDT = "banner_tdt";
	private static final String BANNER_THD = "banner_thd";
	private static final String BANNER = "banner";
	private static final String SUB_TITLE = "SubTitle";
	private static final String IMAGE_SUBTITLE = "ImageSubtitle";
	private static final String DESCRIPTION_FIRST_TITLE = "description";
	private static final String IMAGE_FIRST_TITLE = "image";
	private static final String TOTAL = "total";
	private static final String HREF = "href";
	private static final String MODIFIED_DATE = "modifiedDate";
	private static final String LABEL_DOC = "label";
	private static final String DETAIL_JSP_WCM_WPS_WCM_CONNECT = "detail.jsp?wcm=/wps/wcm/connect/";
	private static final String TEMPLATE = "TempNews";

	public News() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setContentType("application/json");
			// bien json
			PrintWriter out = response.getWriter();
			JSONArray jsonArray = new JSONArray();
			JSONObject json = null;

			int startPage = Integer.parseInt(request.getParameter("StartPage"));
			int pageSize = Integer.parseInt(request.getParameter("PageSize"));
			String site = request.getParameter("Site");
			String library = request.getParameter("Library");
			int k = 1;

			DocumentId siblingId = null;
			DocumentId authoringTmpl = null;
			DocumentId siteArea = null;
			DocumentIdIterator authoringIterator = null;
			DocumentIdIterator siteAreaIterator = null;
			DocumentId<Content> contentid = null;
			DocumentIdIterator<Content> docContent = null;
			String url = "";
			String label = "";
			String image = "";
			String description = "";

			Content content = null;

			Workspace myworkspace = WCM_API.getRepository()
					.getSystemWorkspace();
			myworkspace.login();

			DocumentLibrary MyLibrary = myworkspace.getDocumentLibrary(library);
			myworkspace.setCurrentDocumentLibrary(MyLibrary);

			// find Authoring template
			authoringIterator = myworkspace.findByName(
					DocumentTypes.AuthoringTemplate, TEMPLATE);
			// get authoring template of lib
			authoringTmpl = authoringIterator.next();
			// find Sitearea
			siteAreaIterator = myworkspace.findByName(DocumentTypes.SiteArea,
					site);
			// get siteArea
			if (siteAreaIterator != null && siteAreaIterator.hasNext()) {
				siteArea = siteAreaIterator.next();
			}

			/*
			 * contentSearch(DocumentId templateId, DocumentId[] siteAreaIds,
			 * DocumentId[] categoryIds, java.lang.String[] keywords, boolean
			 * matchAllCategories, boolean includeAncestorCategories, boolean
			 * includeDescendentCategories, boolean includeAncestorSiteAreas,
			 * boolean includeDescendentSiteAreas, java.lang.String sortKey1,
			 * java.lang.String sortKey2, java.lang.String sortKey3, boolean
			 * sortAscending, int workflowStatusFilter)
			 */
			if (siteArea != null) {
				docContent = myworkspace.contentSearch(authoringTmpl,
						new DocumentId[] { siteArea }, null, null, false,
						false, false, false, false,
						Workspace.SORT_KEY_PUBLISH_DATE, null, null, false,
						Workspace.WORKFLOWSTATUS_PUBLISHED);
			} 
			// scan document
			while (docContent.hasNext() && k <= pageSize * startPage) {
				contentid = docContent.next();
				if (k > pageSize * (startPage - 1)) {

					url = "";
					label = "";
					image = "";
					description = "";
					/* khoi tao jsonobject */
					json = new JSONObject();

					content = myworkspace.getById(contentid);

					label = content.getTitle();

					url = DETAIL_JSP_WCM_WPS_WCM_CONNECT + library + "/"
							+ library + "/" + site + "/" + content.getName();

					ImageComponent imageComponent = (ImageComponent) content
							.getComponent(IMAGE_SUBTITLE);
					TextComponent rtDescription = (TextComponent) content
							.getComponent(SUB_TITLE);
					description = rtDescription.getText();
					if (imageComponent.getImageFileName() != null
							&& !"".equals(imageComponent.getImageFileName())) {
						image = StringUtil.replaceMyConnect(imageComponent
								.getResourceURL());
					}

					json.put(LABEL_DOC, label);
					json.put(MODIFIED_DATE, DateUtil.getDate(
							content.getModifiedDate(),
							DateUtil.SHORT_DATE_PATTERN));
					json.put(HREF, url);
					json.put(IMAGE_FIRST_TITLE, image);
					json.put(DESCRIPTION_FIRST_TITLE, description);
					// add vao mang jsonarray
					jsonArray.add(json);
				}
				k++;
			}

			// cau hinh va gui ket qua phan trang
			Pagination pagination = new Pagination();
			PaginationBO paginationBO = new PaginationBO();

			paginationBO.setCurrentPage(startPage);
			paginationBO.setTotalRecord(docContent.getCount());
			paginationBO.setLimit(pageSize);
			paginationBO.setRange(9);
			paginationBO.setLinkFull("news.jsp?site=" + site + "&page={page}");
			paginationBO.setLinkFirst("news.jsp?site=" + site + "&page=1");

			pagination.init(paginationBO);

			json = new JSONObject();
			json.put("pagination", pagination.html());
			jsonArray.add(json);

			jsonArray.add(getSubBanner(myworkspace, site));

			out.print(jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	public JSONObject getSubBanner(Workspace myworkspace, String site) {
		String imageSubBannerName = "";
		DocumentIdIterator imageSubBannerIter = null;
		DocumentId imageSubBannerId = null;
		LibraryImageComponent imageSubBanner = null;
		JSONObject json = new JSONObject();
		try {

			if (Constant.THD.equals(site)) {
				imageSubBannerName = BANNER_THD;
			} else if (Constant.TDT.equals(site)) {
				imageSubBannerName = BANNER_TDT;
			} else if (Constant.TIN_CNTT.equals(site)) {
				imageSubBannerName = BANNER_TINCNTT;
			} else if (Constant.SPDV.equals(site)) {
				imageSubBannerName = BANNER_SPDV;
			}
			imageSubBannerIter = myworkspace.findByName(
					DocumentTypes.ImageComponent, imageSubBannerName);
			imageSubBannerId = (DocumentId) imageSubBannerIter.next();
			imageSubBanner = (LibraryImageComponent) myworkspace
					.getById(imageSubBannerId);

			json.put(BANNER, StringUtil.replaceMyConnect(imageSubBanner
					.getResourceURL()));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return json;
	}

}
